package com.easyj.admin.edu.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import com.easyj.base.common.export.ExpExcutor;
import com.easyj.base.common.export.ExpField;
import com.easyj.base.util.DateTimeUtil;
import com.easyj.base.common.page.PageFilter;
import com.easyj.base.common.ajax.Result;
import com.easyj.base.controller.BaseController;
import com.easyj.base.exception.EasyjException;
import com.easyj.base.exception.ValidateException;
import com.easyj.base.common.page.Page;
import com.easyj.admin.activiti.vo.SimpleApproveVO;
import com.easyj.admin.db.model.Leave;
import com.easyj.admin.db.model.LeaveQO;
import com.easyj.admin.edu.service.LeaveService;
import com.easyj.admin.sys.service.DepartmentService;

	/**
	* 员工请假
	*
	 */
	@RestController
	@RequestMapping(value = "/edu/leave")
	public class LeaveController extends BaseController{

		@Autowired
		private  LeaveService leaveService;
		
		@Autowired
		private  DepartmentService departmentService;
		
		

		/**
		 * get
		 * @param id
		 * @return
		 */
	    @GetMapping("/{id}")
	    public Result get(@PathVariable("id") Long id) {
	        Leave entity = leaveService.findById(id);
	        return Result.Success(entity);
	    }
	    

		@RequestMapping(value = "findCommentsById", method = RequestMethod.GET)
		public Result findCommentsById(@RequestParam(value = "id") Long id) {
			return Result.Success(leaveService.findCommentsById(id));
			
		}
		
		/**
		* 新增申请
		 * @throws EasyjException 
		*/
		@PreAuthorize("hasPermission('leave','leave:apply')")
		@PostMapping(value = "apply")
		public Result apply(@RequestBody @Validated Leave entity,BindingResult validResult) throws EasyjException {
			
            if(validResult.hasErrors()) {
				throw new ValidateException("数据不符合要求！");
			} 			
			leaveService.apply(entity);
			return Result.Success();			
		}
		
		/**
		* 查询自己的申请
		* @param filter
		* @return
		 */

		@PostMapping(value = "findSelf")
		public Result findSelf(@RequestBody  LeaveQO filter) {
			
		    if(filter.getPage().getLimit()>MaxLimit) {
				return Result.Error(10009,"超出一次读取最大行数"); 
			}
		   //set applicantId
		    filter.setApplicantId(this.getUserId());
			Page<Leave>  page =leaveService.findPage(filter);
			
			/*进一步处理数据...
			if(page!=null && page.getRows()!=null ){
				for(Leave v: page.getRows()) {
					//to do-------
					//v.setClassName(classOrgService.findById(v.getClassId()).getName());
				}
			}
			*/
			return Result.Success(page);
			
		}
		
		/**
		* 修改自己的申请
		*/
		@PutMapping
		public Result update(@RequestBody @Validated Leave entity,BindingResult validResult) {
			try{
                if(validResult.hasErrors()) {
					throw new ValidateException("数据不符合要求！");
				}  			
				leaveService.updateEntity(entity);
				return Result.Success();
			}catch(EasyjException ex){
				return Result.Error(ex.getCode(),ex.getMessage()); 
			}catch(Exception ex){
			   log.error("LeaveController.update", ex);
			   return Result.Error("修改错误！"+ex.getMessage()); 
			}
		}

		
		
		 /**
 		 *取消自己的申请
		 * @throws EasyjException 
 		*/
		@RequestMapping(value = "cancel", method = RequestMethod.GET)
 		public Result cancel(@RequestParam(value = "id") Long id) throws EasyjException{
			leaveService.cancel(id);
			return Result.Success();			
 		}
			

		
        /**
		  * 审批
         * @throws EasyjException 
		 */
		@PostMapping(value = "approve")
		public Result approve(@RequestBody @Validated SimpleApproveVO entity,BindingResult validResult) throws EasyjException {
            if(validResult.hasErrors()) {
				throw new ValidateException("数据不符合要求！");
			} 
            entity.setApproveUserId(this.getUserId());
            
			leaveService.approve(entity);
			return Result.Success();
			
		}
		
		/**
		  * 审核
       * @throws EasyjException 
		 */
		@PostMapping(value = "auditApply")
		public Result auditApply(@RequestBody @Validated SimpleApproveVO entity,BindingResult validResult) throws EasyjException {
			
          if(validResult.hasErrors()) {
				throw new ValidateException("数据不符合要求！");
		  } 
          entity.setApproveUserId(this.getUserId());
          
          leaveService.auditApply(entity);
		  return Result.Success();
			
		}
		
		 private void preHandelFilter(LeaveQO filter) throws EasyjException {			
		  		if(filter.getDeptId()!=null) {
		  			List<Long> dptids=departmentService.getDesendantIds(filter.getDeptId(),false);
		  			if(dptids==null||dptids.size()==0) {
		  				throw new EasyjException(EasyjException.DataError,"数据错误，部门不存在！");	
		  			}else {
		  				filter.setDeptIds(dptids);
		  			}
		  		}
			}
 		
 		/**
		* 分页查询
		* @param filter
		* @return
 		 * @throws EasyjException 
		 */
		@PreAuthorize("hasPermission('leave','leave:list')")
		@PostMapping(value = "findPage")
		public Result findPage(@RequestBody  LeaveQO filter) throws EasyjException {			
		    if(filter.getPage().getLimit()>MaxLimit) {
				return Result.Error(10009,"超出一次读取最大行数"); 
			}
		    preHandelFilter(filter);
			Page<Leave>  page =leaveService.findPage(filter);			
			return Result.Success(page);
			
		}
		

      /**
		* 导出Excel
		* @param filter
		* @param expFields
		* @param response
		*/
		@PreAuthorize("hasPermission('leave','leave:list;leave:approve')")
		@RequestMapping(value = "export", method = RequestMethod.POST)
		public void export(@RequestBody LeaveQO filter, HttpServletResponse response){
			try {
				 //导出的字段		
				List<ExpField> fields = new ArrayList<ExpField>();
				fields.add(new ExpField("applyName","申请标题",""));
			      fields.add(new ExpField("applicantName","申请人",""));
			      fields.add(new ExpField("deptName","所属部门",""));			      
			      fields.add(new ExpField("typeName","假期类型","",""));			      
			      fields.add(new ExpField("reason","请假原因",""));
			      fields.add(new ExpField("startTime","开始时间","","datetime"));
			      fields.add(new ExpField("endTime","结束时间","","datetime"));
			      fields.add(new ExpField("totalDays","请假天数",""));
			      fields.add(new ExpField("applyTime","申请时间","","datetime"));
			      fields.add(new ExpField("approveName","审批人",""));
			      fields.add(new ExpField("approveTime","审批时间","","datetime"));
			      fields.add(new ExpField("approveComment","审批意见",""));
			      fields.add(new ExpField("statusName","状态",""));
			    
				//生成 excel
			    preHandelFilter(filter);
				SXSSFWorkbook workbook=exportExcel(filter, fields);
				response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
				String filename="员工请假"+DateTimeUtil.getDateStr8(new Date())+".xlsx";
				String newFileName=URLEncoder.encode(filename,"UTF-8");
				response.setHeader("Content-disposition", "attachment;filename=" + newFileName); 
				OutputStream ouputStream = response.getOutputStream();  
				workbook.write(ouputStream);  
				ouputStream.flush();  
				ouputStream.close();  
			} catch (Exception ex) {
				log.error("LeaveController.export", ex);
			} 
		}
		
		/**
		* 导出excel,生成workbook 
		*/
		private SXSSFWorkbook exportExcel(final LeaveQO filter,List<ExpField> fields) {
			ExpExcutor<Leave>  expExcutor=new ExpExcutor<Leave>(){
				@Override
				protected Long getRecordCount() {
					return leaveService.count(filter);
				}

				@Override
				protected List<Leave> getSheetData(int sheetSize, int sheetinx) {
					PageFilter queryPage=new PageFilter(sheetSize,sheetinx+1);
					filter.setPage(queryPage);
					List<Leave> datas= leaveService.findList(filter);
					
					/*进一步处理数据...
					if(datas!=null ){
						for(Leave v: datas) {
							//v.setClassName(classOrgService.findById(v.getClassId()).getName());
						}
					} */
					return datas;
				}
			};
			SXSSFWorkbook workbook=expExcutor.export(fields,false);
			return workbook;
		}	
		
}

